import 'dart:convert';
import 'alger_api_service.dart';
import 'package:http/http.dart' as http;
import '../models/song.dart';
import '../models/api_response.dart';
import '../models/music_source.dart';

class MusicApiService {
  static const String baseUrl = 'https://music-api.gdstudio.xyz/api.php';
  
  final http.Client _client = http.Client();
  
  // 请求超时时间
  static const Duration _timeout = Duration(seconds: 15);
  
  // 最大重试次数
  static const int _maxRetries = 3;
  
  // 通用请求头
  static const Map<String, String> _headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Connection': 'keep-alive',
  };

  /// 带重试机制的HTTP GET请求
  Future<http.Response> _makeRequest(Uri uri, {int retryCount = 0}) async {
    try {
      print('发起请求 (尝试 ${retryCount + 1}/$_maxRetries): $uri');
      
      final response = await _client.get(uri, headers: _headers).timeout(_timeout);
      
      if (response.statusCode == 200) {
        print('请求成功: ${response.statusCode}');
        return response;
      } else if (response.statusCode == 403 && retryCount < _maxRetries - 1) {
        print('收到403错误，等待后重试...');
        await Future.delayed(Duration(seconds: (retryCount + 1) * 2));
        return _makeRequest(uri, retryCount: retryCount + 1);
      } else {
        throw Exception('HTTP ${response.statusCode}: ${response.body}');
      }
    } catch (e) {
      print('请求失败 (尝试 ${retryCount + 1}/$_maxRetries): $e');
      
      if (retryCount < _maxRetries - 1) {
        print('等待 ${(retryCount + 1) * 2} 秒后重试...');
        await Future.delayed(Duration(seconds: (retryCount + 1) * 2));
        return _makeRequest(uri, retryCount: retryCount + 1);
      } else {
        throw Exception('网络请求失败，已重试 $_maxRetries 次: $e');
      }
    }
  }

  ///米兔热门、随机、新歌
  ///type: hot, new, rand
  Future<List<Song>> getMituMusic({
    required String type,
    int count = 20,
  }) async {
    final Uri uri;
    if (type == 'hot') {
         uri = Uri.parse('https://api.qqmp3.vip/api/songs.php');
    }else{
        uri = Uri.parse('https://api.qqmp3.vip/api/songs.php').replace(queryParameters: {
          'type': type,
        });
    }
    final response = await _makeRequest(uri);
    if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          List<dynamic> list;
          if (jsonData is Map) {
            if (jsonData.containsKey('data')) {
              final data = jsonData['data'];
              if (data is List) {
                list = List<dynamic>.from(data);
              } else{
                throw Exception('米兔音乐 响应格式不支持(data 非列表/无 list): $jsonData');
              }
            } else {
              throw Exception('米兔音乐 响应缺少 data/list: $jsonData');
            }
          } else if (jsonData is List) {
            list = jsonData;
          } else {
            throw Exception('米兔音乐 响应格式不支持: $jsonData');
          }

          final songs = <Song>[];
          for (final item in list) {
            if (item is Map) {
              // 兼容 id/rid
              final id = (item['id'] ?? item['rid'] ?? item['songId'] ?? item['mid'])?.toString() ?? '';
              // 标题字段兼容
              final title = item['title']?.toString() ?? (item['name']?.toString() ?? '');
              // 歌手字段兼容
              final singerRaw = item['singer']?.toString() ?? (item['artist']?.toString() ?? '');
              // 专辑字段兼容
              final album = item['album']?.toString() ?? (item['specialname']?.toString() ?? (item['albumName']?.toString() ?? ''));
              // 图片字段兼容
              var picUrl = item['picurl']?.toString() ?? (item['pic']?.toString() ?? (item['img']?.toString() ?? ''));
              if (picUrl.isNotEmpty) {
                // 去掉返回中可能包含的反引号
                picUrl = picUrl.replaceAll('`', '');       
              }

              // 将歌手拆分为列表，按常见分隔符
              final artists = singerRaw
                  .split(RegExp(r'[、,/]|\s+'))
                  .map((e) => e.trim())
                  .where((e) => e.isNotEmpty)
                  .toList();
              if (artists.isEmpty) artists.add('未知歌手');

              // picId 使用完整图片 URL；urlId/lyricId 使用 id（或 rid），以便后续获取播放链接/歌词
              songs.add(
                Song(
                  id: id.isEmpty ? null : id,
                  name: title.isEmpty ? '未知歌曲' : title,
                  artist: artists,
                  album: album,
                  picId: picUrl, // 直接存放图片URL
                  urlId: id,
                  lyricId: '',
                  source: MusicSource.mitu.value,
                ),
              );
            }           
          }
        // 分页与数量控制（米兔音乐接口不支持count/page参数），这里在客户端限制
        return songs.take(count).toList();
    }else{
      throw Exception('米兔音乐 搜索失败: ${response.statusCode}');
    }
  }


  /// 搜索音乐
  /// [keyword] 搜索关键词
  /// [source] 音乐源
  /// [count] 每页数量，默认20
  /// [page] 页码，默认1
  Future<List<Song>> searchMusic({
    required String keyword,
    MusicSource source = MusicSource.netease,
    int count = 20,
    int page = 1,
  }) async {
    try {
      // buguyy(布谷音乐) 走独立接口
      if (source == MusicSource.buguyy) {
        final uri = Uri.parse('https://a.buguyy.top/newapi/search.php').replace(queryParameters: {
          'keyword': keyword,
        });

        final response = await _makeRequest(uri);
        if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          // 兼容结构：{"code":200, data:{list:[...]}} 或 {list:[...]} 或 直接数组
          List<dynamic> list;
          if (jsonData is Map) {
            if (jsonData.containsKey('data') && jsonData['data'] is Map && (jsonData['data'] as Map).containsKey('list')) {
              list = List<dynamic>.from((jsonData['data'] as Map)['list']);
            } else if (jsonData.containsKey('list')) {
              list = List<dynamic>.from(jsonData['list']);
            } else {
              throw Exception('buguyy 响应格式不支持: $jsonData');
            }
          } else if (jsonData is List) {
            list = jsonData;
          } else {
            throw Exception('buguyy 响应格式不支持: $jsonData');
          }

          final songs = <Song>[];
          for (final item in list) {
            if (item is Map) {
              final id = item['id']?.toString() ?? '';
              final title = item['title']?.toString() ?? (item['name']?.toString() ?? '');
              final singerRaw = item['singer']?.toString() ?? (item['artist']?.toString() ?? '');
              final album = item['album']?.toString() ?? (item['specialname']?.toString() ?? '');
              var picUrl = item['picurl']?.toString() ?? (item['pic']?.toString() ?? '');
              if (picUrl.isNotEmpty) {
                // 去掉返回中可能包含的反引号
                picUrl = picUrl.replaceAll('`', '');
              }

              // 将歌手拆分为列表，按常见分隔符
              final artists = singerRaw
                  .split(RegExp(r'[、,/]|\s+'))
                  .map((e) => e.trim())
                  .where((e) => e.isNotEmpty)
                  .toList();
              if (artists.isEmpty) artists.add('未知歌手');

              // picId 使用完整图片 URL；urlId/lyricId 使用 id，以便后续获取播放链接
              songs.add(
                Song(
                  id: id.isEmpty ? null : id,
                  name: title.isEmpty ? '未知歌曲' : title,
                  artist: artists,
                  album: album,
                  picId: picUrl, // 直接存放图片URL
                  urlId: id,
                  lyricId: '',
                  source: source.value,
                ),
              );
            }
          }
          // 分页与数量控制（buguyy接口不支持count/page参数），这里在客户端限制
          return songs.take(count).toList();
        } else {
          throw Exception('buguyy 搜索失败: ${response.statusCode}');
        }
      }

      // 米兔音乐走独立接口
      if (source == MusicSource.mitu) {
        final uri = Uri.parse('https://api.qqmp3.vip/api/songs.php').replace(queryParameters: {
          'keyword': keyword,
          'type': 'search',
        });

        final response = await _makeRequest(uri);
        if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          // 兼容结构：{"code":200, data:[...]} 或 {data:{list:[...]}} 或 {list:[...]} 或 直接数组
          List<dynamic> list;
          if (jsonData is Map) {
            if (jsonData.containsKey('data')) {
              final data = jsonData['data'];
              if (data is List) {
                list = List<dynamic>.from(data);
              } else{
                throw Exception('米兔音乐 响应格式不支持(data 非列表/无 list): $jsonData');
              }
            } else {
              throw Exception('米兔音乐 响应缺少 data/list: $jsonData');
            }
          } else if (jsonData is List) {
            list = jsonData;
          } else {
            throw Exception('米兔音乐 响应格式不支持: $jsonData');
          }

          final songs = <Song>[];
          for (final item in list) {
            if (item is Map) {
              // 兼容 id/rid
              final id = (item['id'] ?? item['rid'] ?? item['songId'] ?? item['mid'])?.toString() ?? '';
              // 标题字段兼容
              final title = item['title']?.toString() ?? (item['name']?.toString() ?? '');
              // 歌手字段兼容
              final singerRaw = item['singer']?.toString() ?? (item['artist']?.toString() ?? '');
              // 专辑字段兼容
              final album = item['album']?.toString() ?? (item['specialname']?.toString() ?? (item['albumName']?.toString() ?? ''));
              // 图片字段兼容
              var picUrl = item['picurl']?.toString() ?? (item['pic']?.toString() ?? (item['img']?.toString() ?? ''));
              if (picUrl.isNotEmpty) {
                // 去掉返回中可能包含的反引号
                picUrl = picUrl.replaceAll('`', '');       
              }

              // 将歌手拆分为列表，按常见分隔符
              final artists = singerRaw
                  .split(RegExp(r'[、,/]|\s+'))
                  .map((e) => e.trim())
                  .where((e) => e.isNotEmpty)
                  .toList();
              if (artists.isEmpty) artists.add('未知歌手');

              // picId 使用完整图片 URL；urlId/lyricId 使用 id（或 rid），以便后续获取播放链接/歌词
              songs.add(
                Song(
                  id: id.isEmpty ? null : id,
                  name: title.isEmpty ? '未知歌曲' : title,
                  artist: artists,
                  album: album,
                  picId: picUrl, // 直接存放图片URL
                  urlId: id,
                  lyricId: '',
                  source: source.value,
                ),
              );
            }
          }
          // 分页与数量控制（米兔音乐接口不支持count/page参数），这里在客户端限制
          return songs.take(count).toList();
        } else {
          throw Exception('米兔音乐 搜索失败: ${response.statusCode}');
        }
      }

      final uri = Uri.parse(baseUrl).replace(queryParameters: {
        'types': 'search',
        'source': source.value,
        'name': keyword,
        'count': count.toString(),
        'pages': page.toString(),
      });

      final response = await _makeRequest(uri);
      
      print('搜索响应状态码: ${response.statusCode}');
      print('搜索响应内容: ${response.body}');
      
      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        
        // 检查返回的数据格式
        if (jsonData is List) {
          print('搜索结果是List格式，共${jsonData.length}首歌曲');
          return _parseJsonToSongs(jsonData);
        } else if (jsonData is Map && jsonData.containsKey('data')) {
          final List<dynamic> data = jsonData['data'];
          print('搜索结果是Map格式，共${data.length}首歌曲');
          return _parseJsonToSongs(data);
        } else {
          print('意外的响应格式: $jsonData');
          throw Exception('Unexpected response format: $jsonData');
        }
      } else {
        print('搜索请求失败: ${response.statusCode} - ${response.body}');
        throw Exception('Failed to search music: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error searching music: $e');
    }
  }

  /// 获取歌曲播放URL
  /// [songId] 歌曲ID
  /// [source] 音乐源
  /// [quality] 音质
  /// 米兔音乐多一个lrc返回值，用于获取歌词
  Future<(String?, String?)> getSongUrl({
    required String songId,
    required MusicSource source,
    AudioQuality quality = AudioQuality.high,
  }) async {
    try {
      // buguyy(布谷音乐) 获取播放链接
      if (source == MusicSource.buguyy) {
        final uri = Uri.parse('https://a.buguyy.top/newapi/geturl2.php').replace(queryParameters: {
          'id': songId,
        });
        final response = await _makeRequest(uri);
        if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          String? candidateUrl;
          if (jsonData is Map) {
            // 新格式：{"code":200, "data": { url: "..." }}
            if (jsonData.containsKey('data') && jsonData['data'] is Map) {
              final data = Map<String, dynamic>.from(jsonData['data']);
              candidateUrl = data['url']?.toString();
              // 兜底：某些实现可能仍放在 downurl/ktmdownurl（混合格式）
              candidateUrl ??= data['downurl']?.toString();
              candidateUrl ??= data['ktmdownurl']?.toString();
            } else {
              // 旧格式：直接包含 url/downurl/ktmdownurl
              candidateUrl = (jsonData['url'] ?? jsonData['downurl'] ?? jsonData['ktmdownurl'])?.toString();
            }
          } else if (jsonData is String) {
            candidateUrl = jsonData;
          }

          // 规范化与提取真正的可播放 URL
          if (candidateUrl != null) {
            var url = candidateUrl.trim();
            // 去除反引号与多余空格
            url = url.replaceAll('`', '').trim();
            // 处理混合格式：例如 "FLAC# https://... ###MP3# https://..."
            if (url.contains('###MP3#')) {
              final parts = url.split('###MP3#');
              final mp3Part = parts.isNotEmpty ? parts.last : url;
              // 提取其中的第一个 http 链接
              final match = RegExp(r'https?://\S+').firstMatch(mp3Part);
              if (match != null) {
                url = match.group(0)!;
              }
            }
            // 如果仍包含多个片段，优先取第一个 http 链接
            final httpMatch = RegExp(r'https?://\S+').firstMatch(url);
            if (httpMatch != null) {
              url = httpMatch.group(0)!;
            }
            if (url.isNotEmpty && url.startsWith('http')) {
              return (url, null);
            }
          }
        }
        return (null, null);
      }

      // 米兔音乐 获取播放链接
      if (source == MusicSource.mitu) {
        String? lrc;
        final uri = Uri.parse('https://api.qqmp3.vip/api/kw.php').replace(queryParameters: {
          'rid': songId,
        });
        final response = await _makeRequest(uri);
        if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          if (jsonData is Map && jsonData.containsKey('data')) {
            final Map<String, dynamic> data = Map<String, dynamic>.from(jsonData['data']);
            //米兔音乐接口返回的歌词数据
            if (data.containsKey('lrc')) {
              lrc = data['lrc']?.toString();
            }
            if (data.containsKey('url')) {
              return (data['url']?.toString(), lrc);
            }
          }
        }
        return (null, null);
      }


      final uri = Uri.parse(baseUrl).replace(queryParameters: {
        'types': 'url',
        'source': source.value,
        'id': songId,
        'br': quality.bitrate.toString(),
      });

      final response = await _makeRequest(uri);
      
      print('响应状态码: ${response.statusCode}');
      print('响应内容: ${response.body}');
      
      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        
        if (jsonData is Map) {
          print('解析的JSON数据: $jsonData');
          
          if (jsonData.containsKey('url')) {
            final urlResponse = UrlResponse.fromJson(Map<String, dynamic>.from(jsonData));
            print('获取到的URL: ${urlResponse.url}');
            return (urlResponse.url, null);
          } else {
            print('响应中没有url字段');
            // 检查是否有错误信息
            if (jsonData.containsKey('error')) {
              print('API错误: ${jsonData['error']}');
            }
            if (jsonData.containsKey('msg')) {
              print('API消息: ${jsonData['msg']}');
            }
          }
        } else {
          print('响应不是Map格式: $jsonData');
        }
      } else {
        print('HTTP请求失败: ${response.statusCode} - ${response.body}');
      }
      return (null, null);
    } catch (e) {
      print('获取歌曲URL时发生错误: $e');
      return (null, null);
    }
  }

  /// 获取专辑图片URL
  /// [picId] 专辑图片ID
  /// [source] 音乐源
  /// [size] 图片尺寸，300或500
  Future<String?> getAlbumPicture({
    required String picId,
    required MusicSource source,
    int size = 300,
  }) async {
    try {
      // buguyy(布谷音乐) 的 picId 已存放为完整图片URL，直接返回
      if (source == MusicSource.buguyy || source == MusicSource.mitu) {
        if (picId.isNotEmpty && picId.startsWith('http')) {
          return picId;
        }
        return null;
      }

      final uri = Uri.parse(baseUrl).replace(queryParameters: {
        'types': 'pic',
        'source': source.value,
        'id': picId,
        'size': size.toString(),
      });

      final response = await _makeRequest(uri);
      
      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        
        if (jsonData is Map && jsonData.containsKey('url')) {
          final picResponse = PicResponse.fromJson(Map<String, dynamic>.from(jsonData));
          return picResponse.url.isNotEmpty ? picResponse.url : null;
        }
      }
      return null;
    } catch (e) {
      print('Error getting album picture: $e');
      return null;
    }
  }

  /// 获取歌词
  /// [lyricId] 歌词ID
  /// [source] 音乐源
  Future<Map<String, String?>> getLyrics({
    required String lyricId,
    required MusicSource source,
  }) async {
    try {
      // buguyy(布谷音乐) 暂不提供歌词接口，返回空
      if (source == MusicSource.buguyy || source == MusicSource.mitu) {
        return {'lyric': null, 'tlyric': null};
      }

      final uri = Uri.parse(baseUrl).replace(queryParameters: {
        'types': 'lyric',
        'source': source.value,
        'id': lyricId,
      });

      final response = await _makeRequest(uri);
      
      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        
        if (jsonData is Map) {
          final lyricResponse = LyricResponse.fromJson(Map<String, dynamic>.from(jsonData));
          return {
            'lyric': lyricResponse.lyric,
            'tlyric': lyricResponse.tlyric,
          };
        }
      }
      return {'lyric': null, 'tlyric': null};
    } catch (e) {
      print('Error getting lyrics: $e');
      return {'lyric': null, 'tlyric': null};
    }
  }

  /// 兜底：按歌曲名与歌手在常见音乐源中搜索并尝试获取歌词
  /// 用于当前音乐源返回无歌词或没有 lyricId 的场景（如 buguyy）。
  Future<Map<String, String?>> getLyricsFallbackBySearch({
    required Song song,
    required MusicSource source,
    List<MusicSource>? candidateSources,
  }) async {
    // 优先来源顺序：与用户常用平台相近以提高匹配成功率
    final sources = candidateSources ?? const [
      MusicSource.netease,
      MusicSource.kuwo,
      MusicSource.tencent,
      MusicSource.kugou,
      MusicSource.migu,
    ];

    String normalize(String s) => s
        .replaceAll(RegExp(r'\s+'), '')
        .replaceAll(RegExp(r'（.*?）|\(.*?\)|\[.*?\]|\{.*?\}'), '')
        .toLowerCase();
    final targetName = normalize(song.name);
    final targetArtist = song.artist.isNotEmpty ? normalize(song.artist.first) : '';
    final keyword = song.artist.isNotEmpty ? '${song.name} ${song.artist.first}' : song.name;

    for (final s in sources) {
      try {
        // 搜索歌曲
        final results = await searchMusic(keyword: keyword, source: s, count: 5, page: 1);
        Song? best;
        for (final r in results) {
          final nameOk = normalize(r.name) == targetName;
          final artistOk = r.artist.isNotEmpty ? normalize(r.artist.first) == targetArtist : true;
          if (nameOk && artistOk) {
            best = r;
            break;
          }
        }
        best ??= results.isNotEmpty ? results.first : null;
        if (best != null) {
          final idForLyric = best.lyricId.isNotEmpty ? best.lyricId : (best.urlId.isNotEmpty ? best.urlId : best.effectiveId);
          if (idForLyric.isNotEmpty) {
            final lyr = await getLyrics(lyricId: idForLyric, source: s);
            final text = lyr['lyric'];
            if (text != null && text.isNotEmpty) {
              return lyr;
            }
          }
        }
      } catch (e) {
        print('歌词兜底在 ${s.value} 失败: $e');
      }
    }
    return {'lyric': null, 'tlyric': null};
  }

  /// 获取完整的歌曲信息（包括播放URL、专辑图片、歌词）
  Future<Song> getCompleteSongInfo(Song song, {AudioQuality quality = AudioQuality.high}) async {
    final source = MusicSource.fromString(song.source);
    if (source == MusicSource.alger) {
      try {
        final alger = AlgerApiService();
        final url = await alger.fetchSongUrl(song.effectiveId);
        final (lyric, tlyric) = await alger.fetchLyric(song.effectiveId);
        return song.copyWith(
          audioUrl: url,
          lyric: lyric ?? song.lyric,
          tlyric: tlyric ?? song.tlyric,
        );
      } catch (e) {
        print('Alger 获取完整信息失败: $e');
        return song;
      }
    }
    
    // 尝试获取播放URL，如果失败则尝试不同音质
    final (audioUrl, lrc) = await getSongUrl(songId: song.effectiveId, source: source, quality: quality);
    
    // 如果高音质失败，尝试其他音质
    if (audioUrl == null || audioUrl.isEmpty) {
      print('${song.name} - 尝试使用标准音质获取播放链接...');
      final (audioUrl, lrc) = await getSongUrl(songId: song.effectiveId, source: source, quality: quality);
    }
    
    if (audioUrl == null || audioUrl.isEmpty) {
      print('${song.name} - 尝试使用低音质获取播放链接...');
      final (audioUrl, lrc) = await getSongUrl(songId: song.effectiveId, source: source, quality: quality);
    }

    if (lrc != null && lrc.isNotEmpty) { 
      song.lyric = lrc;
    }
    // 并行获取专辑图片和歌词
    final futures = await Future.wait([
      getAlbumPicture(picId: song.picId, source: source),
      getLyrics(lyricId: song.lyricId, source: source),
    ]);

    final albumImageUrl = futures[0] as String?;
    final lyrics = futures[1] as Map<String, String?>;

    // Map<String, String?> finalLyrics = lyrics;
    // if (finalLyrics['lyric'] == null || (finalLyrics['lyric']?.isEmpty ?? true)) {
    //   // 如果当前源没有歌词或返回空，尝试兜底搜索其他源的歌词
    //   try {
    //     final fallback = await getLyricsFallbackBySearch(song: song,source: source);
    //     if (fallback['lyric'] != null && fallback['lyric']!.isNotEmpty) {
    //       finalLyrics = fallback;
    //     }
    //   } catch (e) {
    //     print('歌词兜底失败: $e');
    //   }
    // }

    return song.copyWith(
      audioUrl: audioUrl,
      albumImageUrl: albumImageUrl,
      lyric: song.lyric ?? lyrics['lyric'],
      tlyric: song.tlyric ?? lyrics['tlyric'],
      // lyric: finalLyrics['lyric'],
      // tlyric: finalLyrics['tlyric'],
    );
  }

  /// 搜索专辑中的歌曲
  Future<List<Song>> searchAlbumTracks({
    required String albumName,
    MusicSource source = MusicSource.netease,
    int count = 50,
    int page = 1,
  }) async {
    return searchMusic(
      keyword: albumName,
      source: MusicSource.fromString('${source.value}_album'),
      count: count,
      page: page,
    );
  }

  /// 获取排行榜歌曲
  /// [rankingType] 排行榜类型：hot(热歌榜), new(新歌榜), western(欧美热歌榜), korean(韩语榜)
  Future<List<Song>> getRankingSongs({
    required String rankingType,
    MusicSource source = MusicSource.netease,
    int count = 50,
  }) async {
    String keyword;
    
    switch (rankingType) {
      case 'hot':
        keyword = '热门';
        break;
      case 'new':
        keyword = '新歌';
        break;
      case 'western':
        keyword = 'Billboard Hot 100 Western Pop English';
        break;
      case 'korean':
        keyword = '韩语';
        break;
      case '90后':
        keyword = '90后';
        break;
      case '大家都在听':
        keyword = '大家都在听';
        break;
      case '80后':
        keyword = '80后';
        break;
      case '车载':
        keyword = '车载';
        break;
      case 'dj':
        keyword = 'DJ';
        break;
      default:
        keyword = '热门歌曲';
    }

    try {
      // 对于欧美和韩语榜，尝试多个关键词搜索以获得更好的结果
      if (rankingType == 'western') {
        final keywords = [
          'Billboard Hot 100',
          'Western Pop English',
          'Top English Songs',
          'American Pop Music'
        ];
        
        List<Song> allSongs = [];
        for (String kw in keywords) {
          try {
            final results = await searchMusic(
              keyword: kw,
              source: source,
              count: count ~/ keywords.length + 5,
            );
            allSongs.addAll(results);
          } catch (e) {
            print('搜索关键词 "$kw" 失败: $e');
          }
        }
        
        // 去重并限制数量
        final uniqueSongs = <String, Song>{};
        for (final song in allSongs) {
          final key = '${song.name}_${song.artist}';
          if (!uniqueSongs.containsKey(key)) {
            uniqueSongs[key] = song;
          }
        }
        
        return uniqueSongs.values.take(count).toList();
      } else if (rankingType == 'korean') {
        final keywords = [
          'K-pop Korean KPOP',
          '韩语歌曲 韩国音乐',
          'BTS BLACKPINK TWICE',
          'Korean Pop Music'
        ];
        
        List<Song> allSongs = [];
        for (String kw in keywords) {
          try {
            final results = await searchMusic(
              keyword: kw,
              source: source,
              count: count ~/ keywords.length + 5,
            );
            allSongs.addAll(results);
          } catch (e) {
            print('搜索关键词 "$kw" 失败: $e');
          }
        }
        
        // 去重并限制数量
        final uniqueSongs = <String, Song>{};
        for (final song in allSongs) {
          final key = '${song.name}_${song.artist}';
          if (!uniqueSongs.containsKey(key)) {
            uniqueSongs[key] = song;
          }
        }
        
        return uniqueSongs.values.take(count).toList();
      } else {
        // 对于热歌榜和新歌榜，使用单一关键词搜索
        return await searchMusic(
          keyword: keyword,
          source: source,
          count: count,
        );
      }
    } catch (e) {
      print('获取排行榜歌曲失败: $e');
      throw Exception('获取排行榜歌曲失败: $e');
    }
  }

  /// 安全解析JSON数据为Song列表，跳过解析失败的项目
  List<Song> _parseJsonToSongs(List<dynamic> jsonList) {
    final List<Song> songs = [];
    int successCount = 0;
    int failureCount = 0;
    
    for (int i = 0; i < jsonList.length; i++) {
      try {
        final item = jsonList[i];
        if (item is Map<String, dynamic>) {
          final song = Song.fromJson(item);
          songs.add(song);
          successCount++;
        } else {
          print('跳过非Map格式的项目 $i: $item');
          failureCount++;
        }
      } catch (e) {
        print('解析第 $i 首歌曲失败: $e');
        print('原始数据: ${jsonList[i]}');
        failureCount++;
      }
    }
    
    print('歌曲解析完成: 成功 $successCount 首，失败 $failureCount 首');
    return songs;
  }

  void dispose() {
    _client.close();
  }
}
